package www.dianbaozu.com.ui.login

import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.FlowPreview
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentSmsLoginBinding
import www.dianbaozu.com.ui.ProxyViewModel
import www.wen.com.common.lib.base.fragment.BaseReceiveSMSFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.ContractEntity
import www.wen.com.common.lib.data.entities.RequestRegisterBody
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.FORGET_REMAINDER_TIME
import www.wen.com.common.lib.helper.loading.KeyHelper.FORGET_SYSTEM_REMAINDER_TIME
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import www.wen.com.common.lib.util.SpUtil

/**
 * @author WEN
 * @Description:短信登录
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class SMSLoginFragment : BaseReceiveSMSFragment<FragmentSmsLoginBinding>(), View.OnClickListener{

    private val smsLoginViewModel: SMSLoginViewModel by viewModels()

    private val proxyViewModel: ProxyViewModel by activityViewModels()

    override val viewModel: BaseViewModel
        get() = smsLoginViewModel

    override fun isEnableLoadingHelper() = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter = TitleBarUniversalAdapter(
            requireActivity(),
            action = ::titleAction
    )

    override fun getLayoutId(): Int = R.layout.fragment_sms_login

    override fun getRecordTimeKey(): String = FORGET_REMAINDER_TIME

    override fun getSystemRecordTimeKey(): String = FORGET_SYSTEM_REMAINDER_TIME

    override fun lazyInitView() {
        super.lazyInitView()
        dataBinding.proxyViewModel = proxyViewModel
        dataBinding.smsLoginViewModel = smsLoginViewModel
    }

    @FlowPreview
    override fun onClick(v: View) {
        when(v.id){
            R.id.AgreeAgreement->{
                smsLoginViewModel.run {
                    mAgree.set(!mAgree.get()!!)
                    mEnabledSubmit.value = mAgree.get()!!
                }
            }
            R.id.strUserAgreement -> {
                nav(R.id.action_smsLoginFragment_to_contractFragment, args = Bundle().apply {
                    putParcelable(KeyHelper.BUNDLE_DATA, ContractEntity("用户协议", "用户协议"))
                })
            }
            R.id.strPrivacyAgreement -> {
                nav(R.id.action_smsLoginFragment_to_contractFragment, args = Bundle().apply {
                    putParcelable(KeyHelper.BUNDLE_DATA, ContractEntity("隐私政策", "隐私政策"))
                })
            }
            R.id.btnLogin->{
                requestSmsLogin()
            }

            R.id.slVerificationCode->{
                sendVerificationCode(
                    dataBinding.tvPhoneNumber,
                    dataBinding.etVerificationCode,
                    proxyViewModel.itac.value!!,
                    smsLoginViewModel
                )
            }
            R.id.tvCountryAreaCode->{
                showAreaPopupView()
            }
        }
    }

    private fun showAreaPopupView() {
        CreateXPopupHelper.createBottomAreaCodeListPopupView(PopupViewEntity().apply {
            this.context = requireActivity()
            isShow = true
            itac = proxyViewModel.itac.value!!
            areaCodeList = proxyViewModel.areaCodeEntities.value
            areaCodeListResultCallBack = {
                "+${it.code}".also { area ->
                    dataBinding.tvCountryAreaCode.text = area
                }
                proxyViewModel.itac.value = it.code
                SpUtil.encode(KeyHelper.MMKV_ITAC, it.code)
            }
        })
    }

    /**
     * 注册并登陆
     */
    @FlowPreview
    private fun requestSmsLogin() {

        if(smsLoginViewModel.mPhone.value.isNullOrBlank()) {
            toast("手机号码不能为空")
            return
        }
        if(smsLoginViewModel.mVerificationCode.value.isNullOrBlank()) {
            toast("验证码不能为空")
            return
        }
        if(!smsLoginViewModel.mAgree.get()!!) {
            toast("请勾选协议")
            return
        }

        smsLoginViewModel.requestSmsLogin(
            RequestRegisterBody(
                    mobile = dataBinding.tvPhoneNumber.trimProxy(),
                    smsCode = dataBinding.etVerificationCode.trimProxy(),
            )
        ) { loginInfo ->
            if(loginInfo == null){
                toast("登录失败")
            }else{
                if (loginInfo.user.forbidStatus) {
                    CreateXPopupHelper.createInformPopupView(PopupViewEntity().apply {
                        isShow = true
                        context = requireActivity()
                        title = getString(R.string.the_count_is_ban)
                        content = "因以下原因,用户「${loginInfo.user.nickName}」 已被封禁：\n\n【${loginInfo.user.forbidReason}】\n\n在 ${loginInfo.user.unForbidTime}之前，该账号不能进行登录"
                        confirmContent = getString(R.string.got_it)
                        confirmFunction = {
                            it.dismiss()
                        }
                    })
                } else {
                    requireActivity().resetStartDestination(R.navigation.navigation, R.id.mainFragment)
                }
            }

        }
    }

}



